import {authKey} from "@/config/constant";
import {matchRouters, setDefaultRoute} from "@/utils/menuUtil";
import dynamicRouter from "@/router/dynamic";
import {defaultDynamicRoutes, resetRouter} from "@/router";
import router from "@/router";
import {userDetailInfo} from "@/api/index";

export default {
    namespaced: true,
    state: {
        // 用户 token
        get userToken() {
            return localStorage.getItem(authKey);
        },
        set userToken(userToken) {
            localStorage.setItem(authKey, userToken);
        },
        // 用户基本信息
        userInfo: {},
        // 权限信息
        permissions: [],
        // 菜单
        routerList: []
    },
    mutations: {
        // 登录处理
        USER_LOGIN(state, token) {
            state.userToken = token;
        },
        // 登出处理
        USER_LOGOUT(state) {
            state.userToken = "";
        },
        // 设置用户基本信息
        USER_INFO(state, userInfo) {
            state.userInfo = userInfo;
        },
        // 清除用户基本信息
        CLEAR_USER_INFO(state) {
            state.userInfo = {};
        },
        // 设置可操作权限
        PERMISSIONS(state, permissions) {
            state.permissions = permissions;
        },
        CLEAR_PERMISSIONS(state) {
            state.permissions = [];
        },
        // 设置路由菜单
        SET_MENUS(state, menus) {
            state.routerList = menus;
        },
        CLEAR_MENUS(state) {
            state.routerList = [];
        }
    },
    actions: {
        async userInfo_menus_permissions({commit}) {
            try {
                let userInfo_menus_permissions = await userDetailInfo();
                // console.info(JSON.parse(userInfo_menus_permissions))
                // 获取 userInfo 中用户信息
                let {
                    userInfo
                } = userInfo_menus_permissions;
                commit("USER_INFO", userInfo);
                // 获取权限信息
                let {
                    permissions
                } = userInfo_menus_permissions;
                commit("PERMISSIONS", permissions);
                // 获取菜单信息
                let {menus} = userInfo_menus_permissions;
                // 权限进行对比 后端
                let realRouter = matchRouters(menus, dynamicRouter);
                // 添加子路由
                defaultDynamicRoutes[0].children.push(...realRouter);
                // 添加菜单
                commit("SET_MENUS", defaultDynamicRoutes[0].children);
                // 设置跳转路径
                setDefaultRoute([defaultDynamicRoutes[0]]);
                // 获取到路由 来 初始化路由
                router.addRoutes(defaultDynamicRoutes);
            } catch (e) {
                // 出异常就让用户退出
            }
        },
        logoutUser({commit}) {
            commit("USER_LOGOUT");
            commit("CLEAR_USER_INFO");
            commit("CLEAR_PERMISSIONS");
            commit("CLEAR_MENUS");
            localStorage.clear();
        }
    }
}

